package service

import (
	"os"

	"gopkg.in/yaml.v3"
)

type Config struct {
	ConfigFile string                `yaml:"-"`
	ServerList map[string]ServerInfo `yaml:"server_list,omitempty"`
}

type ServerInfo struct {
	Host       string `yaml:"host,omitempty"`
	User       string `yaml:"user,omitempty"`
	Password   string `yaml:"password,omitempty"`
	PrivateKey string `yaml:"private_key,omitempty"`
}

func GetConfig() (*Config, error) {

	homeDir, err := os.UserHomeDir()
	if err != nil {
		return nil, err
	}

	configpath := homeDir + "/.config/ssh-connect.yml"
	file, err := os.OpenFile(configpath, os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	configByte, err := os.ReadFile(configpath)
	if err != nil {
		return nil, err
	}

	config := Config{
		ConfigFile: configpath,
	}
	if err = yaml.Unmarshal(configByte, &config); err != nil {
		return nil, err
	}

	if config.ServerList == nil {
		config.ServerList = make(map[string]ServerInfo, 0)
	}

	return &config, nil
}

func (config *Config) AddServer(serverInfo *ServerInfo) error {
	config.ServerList[serverInfo.Host] = *serverInfo
	return config.syncfile()
}

func (config *Config) RemoveServer(name string) error {
	delete(config.ServerList, name)
	return config.syncfile()
}

func (config *Config) syncfile() error {
	data, err := yaml.Marshal(config)
	if err != nil {
		return nil
	}

	file, err := os.OpenFile(config.ConfigFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = file.Write(data)
	if err != nil {
		return err
	}

	return nil
}

func (config *Config) SSHConnect(name string) error {
	serverInfo := config.ServerList[name]
	err := startSsh(serverInfo)
	return err
}
